package com.jeeplus.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jeeplus.increase.domain.Increase;
import com.jeeplus.increase.service.IncreaseService;
import com.jeeplus.resource.domain.Venu;
import com.jeeplus.resource.domain.VenuApply;
import com.jeeplus.resource.domain.VenueStatus;
import com.jeeplus.resource.service.VenuApplyService;
import com.jeeplus.resource.service.VenuService;
import com.jeeplus.resource.service.VenueStatusService;
import com.jeeplus.servicecenter.domain.MyUserRole;
import com.jeeplus.servicecenter.service.MyUserService;
import com.jeeplus.sys.domain.Post;
import com.jeeplus.sys.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@Component
public class IncreaseTrend {

    @Autowired
    private PostService postService;

    @Autowired
    private MyUserService myUserService;

    @Autowired
    private IncreaseService increaseService;

    @Autowired
    private VenuService venuService;

    @Autowired
    private VenueStatusService venueStatusService;

    @Autowired
    private VenuApplyService venuApplyService;

    @Autowired
    private RedisTemplate<String ,Object> redisTemplate;



    //第一周组织增长人数
    @Scheduled(cron = "0 0 0 7 * *")
    public void increaseTrendWeekOne(){
        //组织
        List<Post> list = postService.getBaseMapper().selectList(new QueryWrapper<Post>().select("id"));
        for (Post item :list) {
            int countPost = myUserService.count(new QueryWrapper<MyUserRole>().eq("post_id", item.getId()));
            increaseService.update(new UpdateWrapper<Increase>().set("week_one",countPost).eq("post_id",item.getId()));
        }
        //场地
        String nowDate = getNowDate("yyyy-MM-dd").substring(0, 7);
        redisTemplate.opsForValue().set("venueWeek1",
                ""+venuApplyService.count(new LambdaQueryWrapper<VenuApply>()
                        .like(VenuApply::getDate, nowDate)));
    }

    //第二周组织增长人数
    @Scheduled(cron = "0 0 0 14 * *")
    public void increaseTrendWeekTwo(){
        setWeekData("week_two","venueWeek1","venueWeek2");
    }

    //第三周组织增长人数
    @Scheduled(cron = "0 0 0 21 * *")
    public void increaseTrendWeekThree(){
        setWeekData("week_three","venueWeek2","venueWeek3");
    }

    //第四周周组织增长人数
    @Scheduled(cron = "0 0 0 28 * *")
    public void increaseTrendFour(){
        setWeekData("week_four","venueWeek3","venueWeek4");
    }

    //第四周周组织增长人数
    @Scheduled(cron = "0 0 0 29 * *")
    public void increaseTrendFour2(){
        setWeekData("week_four","venueWeek3","venueWeek4");
    }

    //第四周周组织增长人数
    @Scheduled(cron = "0 0 0 30 * *")
    public void increaseTrendFour3(){
        setWeekData("week_four","venueWeek3","venueWeek4");
    }

    //第四周周组织增长人数
    @Scheduled(cron = "0 0 0 31 * *")
    public void increaseTrendFour4(){
        setWeekData("week_four","venueWeek3","venueWeek4");
    }

    public void setWeekData( String postPeopleIncrease , String previousWeek , String nowWeek){
        List<Post> list = postService.getBaseMapper().selectList(new QueryWrapper<Post>().select("id"));
        for (Post item :list) {
            int countPost = myUserService.count(new QueryWrapper<MyUserRole>().eq("post_id", item.getId()));
            increaseService.update(new UpdateWrapper<Increase>().set(postPeopleIncrease,countPost).eq("post_id",item.getId()));
        }
        setVenueWeek(previousWeek, nowWeek);
    }

    /**
     * 设置场地周预约数
     * @param previousWeek
     * @param nowWeek
     */
    public void setVenueWeek(String previousWeek , String nowWeek){
        String nowDate = getNowDate("yyyy-MM-dd").substring(0, 7);
        String previous = (String) redisTemplate.opsForValue().get(previousWeek);
        int now = venuApplyService.count(new LambdaQueryWrapper<VenuApply>()
                .like(VenuApply::getDate, nowDate));
        if (previous != null) {
            int parseInt = Integer.parseInt(previous);
            int result = now - parseInt;
            redisTemplate.opsForValue().set(nowWeek,
                    ""+result);
        }

    }

    /**
     * 获取当前时间
     * @param DateFormat
     * @return
     */
    public String getNowDate(String DateFormat){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(DateFormat);
        return sdf.format(date);
    }

    /**
     * 每天持续增加新的一天场地使用情况
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void insertVenue(){
        List<Venu> list = venuService.list();
        for (Venu venue :list) {
            venueStatusService.save(new VenueStatus(venue));
        }
    }


    /**
     * 更新场地状态为使用中，延迟函数执行后更新为已结束
     * @param time
     */
    public void updateVenueStatus(String time){
        String formattedDate = getNowDate("yyyy-MM-dd");
        venuApplyService.update(new UpdateWrapper<VenuApply>()
                .eq("time",time)
                .like("date",formattedDate)
                .set("status","使用中"));
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.schedule(()->{
            venuApplyService.update(new UpdateWrapper<VenuApply>()
                    .eq("time",time)
                    .like("date",formattedDate)
                    .set("status","已结束"));
        },TimeUnit.HOURS.toMillis(1) + TimeUnit.MINUTES.toMillis(35),TimeUnit.MILLISECONDS);

    }

    /**
     * 每天上午8半点更新场地状态
     */
    @Scheduled(cron = "0 30 8 * * ?")
    public void setAm1(){
        updateVenueStatus("0");
    }

    /**
     * 每天下文两半点更新场地状态
     */
    @Scheduled(cron = "0 30 14 * * ?")
    public void setAm2(){
        updateVenueStatus("1");
    }

    /**
     * 每天下文两半点更新场地状态
     */
    @Scheduled(cron = "0 30 14 * * ?")
    public void setPm1(){
        updateVenueStatus("2");
    }

    /**
     * 每天下文两半点更新场地状态
     */
    @Scheduled(cron = "0 15 16 * * ?")
    public void setPm2(){
        updateVenueStatus("3");
    }

    /**
     * 每天下文两半点更新场地状态
     */
    @Scheduled(cron = "0 30 18 * * ?")
    public void setNight1(){
        updateVenueStatus("4");
    }

    /**
     * 每天下文两半点更新场地状态
     */
    @Scheduled(cron = "0 15 19 * * ?")
    public void setNight2(){
        updateVenueStatus("5");
    }
}
